package edu.isi.pedwork;

import java.sql.*;
import java.util.LinkedList;
import java.util.List;
import java.util.Date;
import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author Qian
 * 
 */
public class Console {
	/**
	 * @param args
	 * @throws TwitterException
	 */

	public static final String dbPath = "jdbc:mysql://pedwork.isi.edu/twitter?"
			+ "user=lord&password=lord";
	Connection conn = null;
	Statement stmt = null;
	int HourRequests = 70;

	public static void main(String[] args) {
		System.out.print("Ready to Work\ninit...");
		Console worker = new Console();
		System.out.println("finish!");
		try {
			worker.init_db();
			worker.run();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public void init_db() throws SQLException {
		System.out.print("init db...");
		conn = DriverManager.getConnection(dbPath);
		stmt = conn.createStatement();
		System.out.println("finish!");
	}

	public void close_db() throws SQLException {
		stmt.close();
		conn.close();
	}

	/*
	 * During one round, we will see a lot of references in tweets, we append
	 * them into a list. Once we at the end of the one round, we process all
	 * these references: 1. If they are already in the twitter id list, we drop
	 * them. 2. If they don't exist in our system, we do the regular procedure
	 * for each new username
	 */
	public void run() throws Exception {
		//
		// tweets_of_user("toptweets",
		// this.db_get_user_by_username("toptweets") == null);
		process_queue();
	}

	private void process_queue() throws Exception {
		String a = null;
		Random r = new Random();
		a = get_one_from_queue();
		while (true) {

			if (a == null) {
				Thread.sleep(10000);
			}

			a = get_one_from_queue();
			if (a != null && !a.equals("")) {
				Driver.getInstance().process(a);
			}
		}

	}

	public String get_one_from_queue() {
		String name = null;
		ResultSet rs = null;
		try {
			rs = stmt
					.executeQuery("SELECT * FROM topic_queue order by date limit 1;");
			if (rs.next()) {
				name = rs.getString("UserId");
				String query = "delete from topic_queue where UserId='" + name
						+ "';";
				int state = stmt.executeUpdate(query);
			}
		} catch (SQLException ex) {
			System.out.println("get one from queue error");
			System.out.println("SQLException: " + ex.getMessage());
			System.out.println("ErrorCode: " + ex.getErrorCode());
		} finally {
			if (rs != null) {
				try {
					rs.close();
				} catch (SQLException sqlEx) {
				} // ignore
				rs = null;
			}
		}
		return name;
	}
}
